var express = require('express');
var router = express.Router();
var moment = require('moment');
var fs = require('fs');
var readline = require('readline');
var exec = require('child_process').exec;
var spawn = require('child_process').spawn;

moment.locale('zh-cn');

const {Readable} = require('stream');
class StringStream extends Readable {
    // #stringToRead;

    constructor(str) {
        super();
        this.stringToRead = str;
    }

    _read() {
        this.push(this.stringToRead);
        this.push(null);
    }
}

//定义读取方法
function read_line(str, callback, callback2) {
    var objReadline = readline.createInterface({
        input: new StringStream(str)
    });
    objReadline.on('line', function (line) {
        callback(line);
    });
    objReadline.on('close', function () {
        callback2();
      });
}

function search_process(req, res) {
    var fn = (function (error, stdout, stderr) {
        // console.log('==stdout==' + stdout);
        var msg = '';
        if (error !== null) {
            msg = '搜索时发生错误: <br/>' + (error + '').replace(/\n/g, '<br/>\n');
        } else if (stderr.length > 0) {
            msg = '搜索时发生错误: <br/>' + (stderr + '').replace(/\n/g, '<br/>\n');
        } else {
            var linenum = 0;
            var arr = [];
            read_line(stdout, function (line) {
                // [32mgopkg.in/tomb.v1[0m ([36mv1.0.0 (dd63297)[0m)
                // console.log("==line==" + line);
                if (linenum % 4 == 0) {
                    line = line.substring(5, line.length - 5);
                    var spStr = '[0m ([36m';
                    var pos = line.indexOf(spStr);
                    if (pos < 0) return;
                    var url = line.substring(0, pos);
                    var version = line.substring(pos + spStr.length);
                    arr.push({url:url,version:version});
                }
                linenum++;
            }, function () {
                msg = JSON.stringify(arr);
                console.log('Search Result: ' + msg);
                res.send(msg);
            });
        }
        // res.render('upload', { title: '依赖提取工具(GO-MOD版)', filekey: fileKey, message: msg });
    });
    return fn;
}

//单个依赖提取服务
router.use('/search/keyword', function (req, res, next) {
    var url = req.query.q;

    if (url && url.length > 0) {
        (function(req, res){
            // 执行命令
            var cmd = '/usr/bin/gosearch ' + url;
            // console.log('[DEBUG]==CMD: ' + cmd);
            exec(cmd, search_process(req, res));
        })(req, res);
    } else {
        res.send('搜索失败');
    }
});

module.exports = router;
